#!/bin/bash
# Clean up LD_PRELOAD
LD_PRELOAD=""

# Check usage
if [ "$#" -lt "2" ]
then
	echo "Usage: `basename \"$0\"` /path/to/executable /path/to/crashdump"
	exit;
fi

# inputs
EXE=$( readlink -f "$1" )
DMP=$( readlink -f "$2" )

# variables
EXENAME=$(basename "${EXE}")
EXEDIR=$(dirname "${EXE}")
DMPNAME=$(basename "${DMP}")
DMPDIR=$(dirname "${DMP}")
FERALHOME="/home/$USER/.local/share/feral-interactive"
CRASHDIR="${DMPDIR}"
DATETIME="$(date +%Y-%m-%d-%H-%M-%S)"
WALKED="${CRASHDIR}/${DATETIME}_crash.log"
WALKLOG="${CRASHDIR}/${DATETIME}_walklog.log"

# Default to local symbols dir, then global
SYMDIR="${EXEDIR}/symbols"
if [[ ! -d $SYMDIR ]]; then
	SYMDIR="${FERALHOME}/symbols"
fi

# try and walk the symbols first
echo "CRASH_REPORTER: Walking the symbols from ${DMPNAME} with ${SYMDIR}"
"${EXEDIR}/minidump_stackwalk" "${DMP}" "${SYMDIR}" 2> "${WALKLOG}" > "${WALKED}"
RESULT=$?

# Check the result for failure
if [[ ! $RESULT == 0 ]]; then
	echo "CRASH_REPORTER: ERROR - walk appears to have failed ${WALKLOG}"
	exit 0
else
	# check the output log for an error on reading the symbols
	HASH=`grep "INFO: Couldn't load symbols for: ${EXENAME}" "${WALKLOG}" | sed 's/.*|//'`

	# if we find a failure to load, output the way to generate these symbols
	if [[ ! -z "$HASH" ]]; then
		echo "CRASH_REPORTER: Crashwalk failed due to lack of symbols"
		echo "CRASH_REPORTER: See https://confluence.feral.co.uk/display/DEV/Crash+Handling"
		echo "CRASH_REPORTER: manually generate symbols with"
		echo "$ mkdir -p \"${SYMDIR}/${EXENAME}/${HASH}\" && \"$EXEDIR/dump_syms\" \"${EXE}\" > \"${SYMDIR}/${EXENAME}/${HASH}/${EXENAME}.sym\""
		echo "CRASH_REPORTER: symbolise this crash with"
		echo "$ \"$( readlink -f "$0" )\" \"$EXE\" \"$DMP\""

		# remove the failed crash
		rm "${WALKED}"
	else
		# otherwise just output the crashwalk
		echo "CRASH_REPORTER: SUCCESS - ${WALKED}"

		# If we have zenity launch a convenience window showing the crash log, but not in BP mode
		if [[ `type -p zenity` ]] && [[ $SteamTenfoot -eq 0 ]]; then
			zenity --text-info --width=600 --height=600 --title="CRASH_REPORTER - ${DATETIME}" --filename="${WALKED}"
		fi
	fi
fi
